"""
爬取直播 以简单的映客直播为例 inke.cn
知识：API、视频 和 websocket
"""
import json

import requests
import datetime
from threading import Thread

# 1. 发现入口 API
hot_list_api = 'https://webapi.busi.inke.cn/web/live_hotlist_pc'
r = requests.get(hot_list_api)
j = r.json()


# 2. 以第一个为例
streamer_info = j['data']['hotlists'][0]
print(streamer_info)

# {'id': 160037391,
#  'level': 113,
#  'nick': '乐儿',
#  'liveid': '1647924956361049',
#  'title': '乐儿',
#  'online_users': 28435}

live_id = streamer_info['liveid']
streamer_id = streamer_info['id']

# 视频流
def download_video(live_id, seconds=-1):
    video_uri = f'https://qqwebhls.inke.cn/live/{live_id}.flv'
    video_r = requests.get(video_uri, stream=True)
    start_time = datetime.datetime.now()
    keep_time = seconds > 0
    with open(f'video_{live_id}.flv', 'wb') as f:
        for chunk in video_r.iter_content(chunk_size=4096):
            f.write(chunk)
            if keep_time:
                delta = datetime.datetime.now() - start_time
                if delta.seconds > seconds: break


# 开启一个线程去下载
Thread(target=download_video,
       args=(streamer_info['liveid'], 2 * 60)).start()


# 弹幕聊天，使用 websocket

from websocket import WebSocketApp


ws = f'wss://chatroom.inke.cn/ws?' \
     'uid=0&' \
     'place=room&' \
     f'roomid={live_id}&' \
     'token=&' \
     f'time={int(datetime.datetime.now().timestamp())}&' \
     'sid=&' \
     'session=10000' \
     f'&_t={int(datetime.datetime.now().timestamp() * 1000)}&' \
     'access_from=pc_web&' \
     f'id={live_id}&' \
     f'roomid={live_id}&' \
     f'uid={streamer_id}'

msg_box = []

def on_message(app, msg: bytes):
    msg_box.append(msg)
    print(msg[:32])

def on_open(app): print('open')

def on_close(app): print('close')

app = WebSocketApp(ws, on_message=on_message,
                   on_open=on_open, on_close=on_close)
app.run_forever()

decoded_msg = [json.loads(msg) for msg in msg_box]


